package com.intelap.rp3.coherence.pruebaConcepto;

import java.awt.List;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.tangosol.net.cache.CacheStore;

public class AlmacenAccessor implements CacheStore {
	private static final Logger log = Logger.getLogger("Almacen");
	private static final String ALMACEN_HOST = "localhost";

	private Almacen almacen;

	public AlmacenAccessor() {
		if (System.getSecurityManager() == null) {
			System.setSecurityManager(new SecurityManager());
		}
		try {
			Registry registry = LocateRegistry.getRegistry(ALMACEN_HOST);
			this.almacen = (Almacen) registry.lookup("Almacen");
		} catch (Exception e) {
			log.log(Level.SEVERE, "Error al buscar el Almacen remoto", e);
		}
	}

	private void logRemoteException(RemoteException e) {
		log.log(Level.SEVERE, "Error al usar el Almacen remoto", e);
	}

	@Override
	public Object load(Object oKey) {
		try {
			return almacen.load((Serializable) oKey);
		} catch (RemoteException e) {
			logRemoteException(e);
			return null;
		}
	}

	@Override
	public Map loadAll(Collection colKeys) {
		try {
			return almacen.loadAll(new ArrayList(colKeys));
		} catch (RemoteException e) {
			logRemoteException(e);
			return null;
		}
	}

	@Override
	public void erase(Object oKey) {
		try {
			almacen.erase((Serializable) oKey);
		} catch (RemoteException e) {
			logRemoteException(e);
		}
	}

	@Override
	public void eraseAll(Collection colKeys) {
		try {
			almacen.eraseAll(new ArrayList(colKeys));
		} catch (RemoteException e) {
			logRemoteException(e);
		}
	}

	@Override
	public void store(Object oKey, Object oValue) {
		try {
			almacen.store((Serializable) oKey, (Serializable) oValue);
		} catch (RemoteException e) {
			logRemoteException(e);
		}
	}

	@Override
	public void storeAll(Map mapEntries) {
		try {
			almacen.storeAll(new HashMap(mapEntries));
		} catch (RemoteException e) {
			logRemoteException(e);
		}
	}

}
